package com.itheima.service;
import com.itheima.mapper.BrandMapper;
import com.itheima.pojo.Brand;
import com.itheima.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;

/**
 * 查询所有
 */
public class BrandService {
    SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();
    public List<Brand> selectAll(){
        //调用BrandMapper.selectAll()

        //2.获取SqlSession
        SqlSession sqlSession = factory.openSession();
        //3.获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //4.调用BrandMapper.selectAll()
        List<Brand> brands = mapper.selectAll();

        sqlSession.close();
        return brands;
    }

    /**
     * 添加
     * @param brand
     */
    public void add(Brand brand){
        //调用BrandMapper.selectAll()

        //2.获取SqlSession
        SqlSession sqlSession = factory.openSession();
        //3.获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //4.调用BrandMapper的add方法
        mapper.add(brand);
        //5.提交事务
        sqlSession.commit();
        //6.关闭资源
        sqlSession.close();

    }

    /**
     * 根据id查询
     * @param id
     * @return
     */
    public Brand selectById(int id){
        //2.获取SqlSession
        SqlSession sqlSession = factory.openSession();
        //3.获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //4.调用BrandMapper的selectById方法
        Brand brand = mapper.selectById(id);
        sqlSession.close();
        return brand;

    }

    /**
     * 修改
     * @param brand
     */
    public void update(Brand brand){
        //调用BrandMapper.selectAll()

        //2.获取SqlSession
        SqlSession sqlSession = factory.openSession();
        //3.获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //4.调用BrandMapper的add方法
        mapper.update(brand);
        //5.提交事务
        sqlSession.commit();
        //6.关闭资源
        sqlSession.close();

    }

    public void deletedById(int id){
        //调用BrandMapper.selectAll()

        //2.获取SqlSession
        SqlSession sqlSession = factory.openSession();
        //3.获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //4.调用BrandMapper的select()
        mapper.delete(id);
        sqlSession.commit();
        sqlSession.close();
    }
}
